package com.example.goodsmanagementcabinet.activity;

import android.app.Dialog;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.goodsmanagementcabinet.R;
import com.example.goodsmanagementcabinet.adapter.UserListAdapter;
import com.example.goodsmanagementcabinet.base.BaseActivity;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;
import com.example.goodsmanagementcabinet.bean.UserBean;
import com.example.goodsmanagementcabinet.db.DatabaseManager;
import com.example.goodsmanagementcabinet.finger.FingerHandler;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.speaker.Speaker_;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Fullscreen
@EActivity(R.layout.activity_user_manager)
public class UserManagerView extends BaseActivity implements View.OnClickListener, AdapterView.OnItemLongClickListener, Handler.Callback {
    @ViewById
    public ListView userGv;
    @ViewById
    Button but_add;
    @ViewById
    Button cancel;
    @ViewById
    ImageView toHome;
    List<UserBean> users = new ArrayList<>();
    UserBean deleteUser;
    public static boolean mCollectState;
    UserListAdapter mAdapter;
    private UserBean user;
    @ViewById
    RelativeLayout mrelativeLsit;
    @ViewById
    LinearLayout layout;
    @ViewById
    SurfaceView sf_view;
    private SurfaceHolder mHolder;
    Dialog userDialog;
    Dialog dialogs;
    Dialog dialog;
    TextView textView;

    @AfterViews
    public void afterViews() {
        mHolder = sf_view.getHolder();
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        toHome.setOnClickListener(this);
        but_add.setOnClickListener(this);
        cancel.setOnClickListener(this);
        mAdapter = new UserListAdapter(this);
        userGv.setAdapter(mAdapter);
        queryUser();
    }


    @Subscribe
    @Background
    public void handlerAttribute(OttoMsg msg) {
        if (TextUtils.equals(OttoMsg.OTTO_INSERT_FINGER, msg.which)) {
            user = (UserBean) msg.data;
            collectFinger();
        } else if (TextUtils.equals(OttoMsg.OTTO_COLLECT_FINGER_SUCESS, msg.which)) {
            String finger = (String) msg.data;
            e(finger);
            DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).insertToFingers(user.getUserId(), "1", finger);
            queryUser();
        } else if (TextUtils.equals(OttoMsg.OTTO_REINSERT_FINGER, msg.which)) {
            user = (UserBean) msg.data;
            deleteDialog("2");
        }
    }


    @Background
    void queryUser() {
        users = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUsers();
        updateUserList();
    }


    @UiThread
    void updateUserList() {
        mAdapter.notifyRefresh(users);
        userGv.setOnItemLongClickListener(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (users != null) {
            users.clear();
            users = null;
        }
        if (user != null) {
            users = null;
        }
        if (deleteUser != null) {
            deleteUser = null;
        }
        dialogDestroy();
        mAdapter = null;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        deleteUser = users.get(position);
        deleteDialog("1");
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_add:
                userDialog();
                break;
            case R.id.toHome:
                FingerHandler.fingerHandler.cancel();
                finish();
                break;
            case R.id.take_photo:
                break;
            case R.id.cancel:
                setView(false);
                break;
        }
    }


//    @UiThread
//    public void Dialogs() {
//        if (dialogs == null) {
//            dialogs = new Dialog(this, R.style.add_dialog);
//            dialogs.setContentView(R.layout.item_pop_delete_user);
//            dialogs.setCancelable(false);
//            WindowManager.LayoutParams layoutParams = dialogs.getWindow().getAttributes();
//            dialogs.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//            dialogs.getWindow().setAttributes(layoutParams);
//            Window dialogsWindow = dialogs.getWindow();
//            dialogsWindow.setGravity(Gravity.CENTER_HORIZONTAL);
//            textView = dialogs.findViewById(R.id.tv_user);
//            Button affirmBtn = dialogs.findViewById(R.id.accptBtn);
//            Button mCancleBtn = dialogs.findViewById(R.id.cancelBtn);
//            //textView = dialogs.findViewById(R.id.)
//            affirmBtn.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dialogs.hide();
//                    setView(true);
//                    start(0);
//                }
//            });
//
//            mCancleBtn.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dialogs.hide();
//                }
//            });
//        }
//        textView.setText("是否重新录取" + user.getNickname() + "的人脸数据");
//        dialogs.show();
//    }


    private void userDialog() {
        if (userDialog == null) {
            userDialog = new Dialog(this, R.style.add_dialog);
            userDialog.setContentView(R.layout.item_new_user);
            userDialog.setCancelable(false);
            WindowManager.LayoutParams layoutParams = userDialog.getWindow().getAttributes();
            userDialog.getWindow().setAttributes(layoutParams);
            Window dialogWindow = userDialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            final EditText mNameTv, muserNoEd, mPassWord;
            mNameTv = userDialog.findViewById(R.id.mNameTv);
            muserNoEd = userDialog.findViewById(R.id.mNoTv);
            mPassWord = userDialog.findViewById(R.id.mPassWordTv);
            Button closebtn = userDialog.findViewById(R.id.mCancel);
            closebtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    userDialog.dismiss();
                }
            });

            Button submit = userDialog.findViewById(R.id.mSubmit);
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String NameTv = mNameTv.getText().toString().trim();
                    String mNoTv = muserNoEd.getText().toString().trim();
                    String password = mPassWord.getText().toString().trim();
                    if (TextUtils.isEmpty(mNoTv) || TextUtils.isEmpty(NameTv) || TextUtils.isEmpty(password)) {
                        t("内容不完整");
                    } else {
                        UserBean query = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUserByusrName(mNoTv);
                        if (query == null) {
                            UserBean userBean = new UserBean();
                            userBean.setNickname(NameTv);
                            userBean.setUserId(mNoTv);
                            userBean.setPassWord(password);
                            users.add(userBean);
                            DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).insertToUser(userBean);
                            mNameTv.setText("");
                            muserNoEd.setText("");
                            updateUserList();
                            userDialog.hide();
                        } else {
                            t("该工号人员已存在，请重新输入");
                            muserNoEd.setText("");
                        }
                    }
                }
            });
        }
        userDialog.show();
    }

    @UiThread
    public void deleteDialog(final String type) {
        if (dialog == null) {
            dialog = new Dialog(this, R.style.add_dialog);
            dialog.setContentView(R.layout.item_pop_delete);
            dialog.setCancelable(false);
            WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            dialog.getWindow().setAttributes(layoutParams);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL);
            textView = dialog.findViewById(R.id.tv_user);
            Button affirmBtn = dialog.findViewById(R.id.accptBtn);
            final Button mCancleBtn = dialog.findViewById(R.id.cancelBtn);
            //textView = dialog.findViewById(R.id.)
            affirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.equals(type, "1")) {
                        users.remove(deleteUser);
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteUserInfo(deleteUser);
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteKeyUserByUserId(deleteUser.getUserId());
                    } else {
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteFingerByUserid(user.getUserId());
                    }
                    queryUser();
                    dialog.hide();

                }
            });

            mCancleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    user = null;
                    dialog.hide();
                }
            });
        }
        if (TextUtils.equals(type, "1")) {
            textView.setText("是否删除" + deleteUser.getNickname() + ":" + deleteUser.getNickname());
        } else {
            textView.setText("是否清空" + user.getNickname() + "的指纹重新录取");
        }
        dialog.show();
    }

    @Background
    public void collectFinger(){
        FingerHandler.getInstance().collect();
    }


    private void dialogDestroy() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        if (userDialog != null) {
            userDialog.dismiss();
            userDialog = null;
        }
        if (dialogs != null) {
            dialogs.dismiss();
            dialogs = null;
        }
    }

    @UiThread
    public void setView(boolean iscamer) {
        if (iscamer) {
            mrelativeLsit.setVisibility(View.GONE);
            layout.setVisibility(View.VISIBLE);
        } else {
            mrelativeLsit.setVisibility(View.VISIBLE);
            layout.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        return true;
    }
}
